package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
//        明文密码
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!pwd.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


    /**
     * 新增员工
     *
     * @param dto
     * @return
     */
    @Override
    public Result addEmp(EmployeeDTO dto) {
        //非空判断
        if (dto.getUsername()==null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //根据账号查询数据库是否存在，若存在则直接返回错误
        Employee employee = employeeMapper.getByUsername(dto.getUsername());
        if (employee!=null){
            return Result.error(MessageConstant.ACCOUNT_EXEIT_FOUND);
        }
        //新增用户  创建人和修改人
        employee = new Employee();

        BeanUtils.copyProperties(dto,employee);

        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        employee.setStatus(StatusConstant.ENABLE);

        employee.setCreateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());


        employeeMapper.addEmp(employee);
        //返回数据
        return Result.success(employee);
    }

    /**
     * 分页查询员工列表
     *
     * @param dto
     * @return
     */
    @Override
    public Result page(EmployeePageQueryDTO dto) {
            if (dto.getPage()==null){
            dto.setPage(1);
        }
        if (dto.getPageSize()==null){
            dto.setPageSize(5);
        }

        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<Employee> pageParam = employeeMapper.pageQuery(dto);

        PageResult pageResult=new PageResult();
        pageResult.setTotal(pageParam.getTotal());
        pageResult.setRecords(pageParam.getResult());

        return Result.success(pageResult);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Result<Employee> getEmpById(Long id) {
        if (id==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        Employee employee = employeeMapper.getEmpById(id);
        employee.setPassword("******");

        return Result.success(employee);
    }

    /**
     * 修改员工信息
     *
     * @param dto
     * @return
     */
    @Override
    public Result updateEmp(EmployeeDTO dto) {
        if (dto.getId()==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        Employee employee=new Employee();
        BeanUtils.copyProperties(dto,employee);//将dto复制给employee
        //修改人和修改时间
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.updateEmp(employee);

        return Result.success();
    }

    /**
     * 启用禁用
     * @param status 状态 0表示禁用1 表示启用
     * @param id  员工id
     * @return
     */
    @Override
    public Result updateEmpStatus(Integer status, Long id) {
        if (id==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        if (status==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        Employee employee=new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.updateEmp(employee);

        return Result.success();
    }


}
